<?php

class Imap {
	
	public static $hostname = '{imap.polytech.unice.fr:993/imap/ssl/novalidate-cert}';
	
	public static function open($mailbox = 'INBOX') {
		$m = imap_open(Imap::$hostname.$mailbox,$_SESSION['user']['username'],$_SESSION['user']['password'])
			or die('Connexion impossible &agrave; '.Imap::$hostname.$mailbox.' : '.imap_last_error());
		return $m;
	}
	
	public static function close($mailbox) {
		imap_close($mailbox);
	}
	
	public static function login($username, $password) {
		return imap_open(Imap::$hostname,$username,$password);
	}
	
	public static function mailbox_status($mailbox) {
		$m = imap_open(Imap::$hostname.$mailbox,$_SESSION['user']['username'],$_SESSION['user']['password']);
		$s = imap_status($m,Imap::$hostname.$mailbox,SA_ALL);
		imap_close($m);
		return $s;
	}
	
	public static function chooseMailbox($mailbox) {
		$mailboxes = array();
		foreach($_SESSION['user']['mailboxes'] as $m) {
			$mailboxes[] = $m->fullname;
		}
		return in_array($mailbox, $mailboxes) ? $mailbox : INBOX;
	}
	
	public static function getMailboxes() {
		$mailboxes = imap_getsubscribed(imap_open(Imap::$hostname,$_SESSION['user']['username'],$_SESSION['user']['password']),Imap::$hostname,'*');
		krsort($mailboxes);
		foreach($mailboxes as $mailbox) {
			$mailbox->fullname = str_replace(Imap::$hostname,'',$mailbox->name);
			$parts = explode($mailbox->delimiter,$mailbox->fullname);
			$mailbox->realname = $parts[count($parts)-1];
			unset($parts[count($parts)-1]);
			$mailbox->parent = implode('.',$parts);
		}
		return $mailboxes;
	}
	
	public static function getCustomMailboxes() {
		$mailboxes = array();
		foreach($_SESSION['user']['mailboxes'] as $mailbox) {
			if($mailbox->fullname != INBOX && $mailbox->fullname != SENT && $mailbox->fullname != TRASH && $mailbox->fullname != DRAFTS) {
				$mailboxes[] = $mailbox;
			}
		}
		return $mailboxes;
	}
	
}
